package com.iSnail.ms.gather.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;

import com.iSnail.ms.util.Const;
import com.iSnail.ms.util.I18N;

public class ModelJTree extends JFrame {

	private JTree tree;
	private DefaultTreeModel model;
	private DefaultMutableTreeNode rootNode;

	public ModelJTree() {
		tree = new JTree();
		DefaultMutableTreeNode philosophersNode = getPhilosopherTree();
		model = new DefaultTreeModel(philosophersNode);
		tree.setModel(model);
		JButton addButton = new JButton("Add Philosopher");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				addPhilosopher();
			}
		});
		JButton removeButton = new JButton("Remove Selected Philosopher");
		removeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				removeSelectedPhilosopher();
			}
		});
		JPanel inputPanel = new JPanel();
		inputPanel.add(addButton);
		inputPanel.add(removeButton);

		Container container = getContentPane();
		container.add(new JScrollPane(tree), BorderLayout.CENTER);
		container.add(inputPanel, BorderLayout.NORTH);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(400, 300);
		setVisible(true);
	}

	private void addPhilosopher() {
		DefaultMutableTreeNode parent = getSelectedNode();
		if (parent == null) {
			JOptionPane.showMessageDialog(ModelJTree.this, "Select an era.", "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		String name = JOptionPane.showInputDialog(ModelJTree.this, "Enter Name:");
		model.insertNodeInto(new DefaultMutableTreeNode(name), parent, parent.getChildCount());
	}

	private void removeSelectedPhilosopher() {
		DefaultMutableTreeNode selectedNode = getSelectedNode();
		if (selectedNode != null)
			model.removeNodeFromParent(selectedNode);
	}

	private DefaultMutableTreeNode getSelectedNode() {
		return (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
	}

	private DefaultMutableTreeNode getPhilosopherTree() {
		rootNode = new DefaultMutableTreeNode(I18N.getString(Const.TREE_ROOT_NAME));
		DefaultTreeCellRenderer cellRenderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
		cellRenderer.setLeafIcon(new ImageIcon("resource/root.png"));

		
		DefaultMutableTreeNode medieval = new DefaultMutableTreeNode(I18N.getString(Const.GATHER_1));
		rootNode.add(medieval);
		
		return rootNode;
	}

	public static void main(String args[]) {
		new ModelJTree();
	}
}